//Dao实现类数据库操作
package com.sy.dao.impl;

import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sy.dao.BaseDao;
import com.sy.util.PageBean;
import com.sy.util.PageInfo;

@SuppressWarnings({ "unchecked", "deprecation" })
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {

//日志
	protected final Log log = LogFactory.getLog(getClass());
	
//保存更新
	public void saveOrUpdateAll(List list) {
		getHibernateTemplate().saveOrUpdateAll(list);
	}
//保存更新
	public void saveOrUpdateObject(Object o) {
		getHibernateTemplate().saveOrUpdate(o);
	}
//插入对象
	public void addObject(Object o) {
		getHibernateTemplate().save(o);
	}
//获取对象
	public Object getObject(Class clazz, Serializable id) {
		Object o = getHibernateTemplate().get(clazz, id);
		if (o == null) {
			throw new ObjectRetrievalFailureException(clazz, id);
		}
		return o;
	}
//获取对象
	public List getObjects(Class clazz) {
		return getHibernateTemplate().loadAll(clazz);
	}
//获取对象
	public List getObjectsByExample(Object o) {
		return getHibernateTemplate().findByExample(o);
	}
//删除对象
	public void removeObject(Class clazz, Serializable id) {
		getHibernateTemplate().delete(getObject(clazz, id));
	}
//动态查询（hibernate3的新增方法）
	
	
	public List findByCriteria(final DetachedCriteria detachedCriteria,
			final int FirstResult, final int MaxResults) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Criteria criteria = detachedCriteria
						.getExecutableCriteria(session);
				List list = criteria.setFirstResult(FirstResult).setMaxResults(
						MaxResults).list();
				return list;
			}
		}, true);
	}
//动态获取总条数
	
	public int getCountByCriteria(final DetachedCriteria detachedCriteria) {
		Integer count = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Criteria criteria = detachedCriteria
								.getExecutableCriteria(session);
						return criteria.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true);
		return count.intValue();
	}
//动态查找分页
	public List findByPage(final DetachedCriteria detachedCriteria,
			PageInfo pageinfo) {

		pageinfo.setTotalResult(getCountByCriteria(detachedCriteria));

		return findByCriteria(detachedCriteria, pageinfo.getBeginResult(),
				pageinfo.getPageSize());

	}
//按HQL查找
	public List findWithPages(final String hqlString, final PageInfo pageInfo) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {

				Query query = session.createQuery(hqlString);
				pageInfo.setTotalResult(getAllRowsCount(hqlString));

				query.setFirstResult(pageInfo.getBeginResult());
				query.setMaxResults(pageInfo.getPageSize());

				return query.list();
			}
		}, true);
	}
//获取分页总行数
	public int getAllRowsCount(String hqlString) {

		List list = getAllRows(hqlString);

		if (list != null) {

			return list.size();
		}
		return 0;
	}
//搜索
	public List findWithPagesByParams(final String hqlString,
			final Object[] objs, final PageInfo pageInfo) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				String hqllow = hqlString.toLowerCase();
				int index = hqllow.indexOf("from");
				String totalhql = hqlString
						.substring(index, hqlString.length());
				totalhql = "select count(*) " + totalhql;
				Query query = session.createQuery(hqlString);
				for (int i = 0; i < objs.length; i++) {
					query.setParameter(i, objs[i]);
				}
				pageInfo.setTotalResult(getAllRowsCount(totalhql, objs)
						.intValue());
				query.setFirstResult(pageInfo.getBeginResult());
				query.setMaxResults(pageInfo.getPageSize());
				return query.list();
			}
		}, true);
	}
//高级搜索
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List findWithPagesByParamsWithOrderby(final String hqlString,
			final Object[] objs, final PageInfo pageInfo, final String field) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				String hqllow = hqlString.toLowerCase();
				int index = hqllow.indexOf("from");
				String totalhql = hqlString
						.substring(index, hqlString.length());
				totalhql = "select count(*) " + totalhql;
				String hql = hqlString + " order by " + field + " desc";
				Query query = session.createQuery(hql);
				if (objs != null) {
					for (int i = 0; i < objs.length; i++) {
						query.setParameter(i, objs[i]);
					}
					pageInfo.setTotalResult(getAllRowsCount(totalhql, objs)
							.intValue());
				} else {
					pageInfo.setTotalResult(getAllRowsCount(totalhql, objs)
							.intValue());
				}
				query.setFirstResult(pageInfo.getBeginResult());
				query.setMaxResults(pageInfo.getPageSize());
				return query.list();
			}
		}, true);
	}
//获取分页总行数
	@SuppressWarnings("deprecation")
	public Integer getAllRowsCount(final String hqlString, final Object[] objs) {

		return (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {

						Integer count;

						Query query = session.createQuery(hqlString);
						if (objs != null)
							for (int i = 0; i < objs.length; i++) {
								query.setParameter(i, objs[i]);
							}
						Integer countobj = (Integer) query.uniqueResult();
						if (countobj != null)
							count = countobj;
						else
							count = new Integer(0);

						return count;
					}
				}, true);

	}
//查询列表
	@SuppressWarnings({ "unchecked", "deprecation" })
	public List getAllRows(final String hqlString) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {

				Query query = session.createQuery(hqlString);

				return query.list();
			}
		}, true);
	}
//获取查询列表
	public List find(String hql, Object[] objs) {

		return getHibernateTemplate().find(hql, objs);

	}
//获取查询列表
	public List find(String hql, Object obj) {

		return getHibernateTemplate().find(hql, obj);

	}
//获取查询列表
	public List find(String hql) {
		return getHibernateTemplate().find(hql);
	}
//分页实现
	public PageBean getPageBean(DetachedCriteria dc, int pageNO, int pageSize) {

		int count = this.getCountByCriteria(dc);
		int pageCount = ((count + pageSize) - 1) / pageSize;
		PageBean pb = new PageBean();
		pb.setPageSize(pageSize);
		pb.setTotalResult(count);
		pb.setPageNo(pageNO);
		pb.setSumPage(pageCount);
		pb.setPageFirstIndex(1);
		pb.setPageLastIndex(pageCount);
		if (pageNO >= pageCount) {
			pb.setLastPage(false);
		} else {
			pb.setLastPage(true);
			pb.setPageLastIndex(pageNO + 1);
		}
		if (pageNO == 1) {
			pb.setFirstPage(false);
		} else {
			pb.setFirstPage(true);
			pb.setPageFirstIndex(pageNO - 1);
		}
		return pb;
	}
//动态分页
	public List getList(DetachedCriteria dc, int pageNO, int pageSize) {
		int sNum = pageSize * (pageNO - 1);
		//DetachedCriteria dc = DetachedCriteria.forClass(Jobtsyspower.class);
		//return this.findByCriteria();
		return this.findByCriteria(dc, sNum, pageSize);
	}
}